package com.bieber.server.netty.handler;

import com.bieber.common.Constants;
import com.bieber.server.pack.FilePackage;
import com.bieber.server.pack.FileStatus;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by bieber on 2015/8/19.
 */
public class NettyHandler extends SimpleChannelInboundHandler<FilePackage>{

    private static final TransporterHandler handler = new ExecutorHandler();

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        Constants.COMMON_LOGGER.info("new remote [{}] socket connected",ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FilePackage filePackage) throws Exception {
        Constants.COMMON_LOGGER.info("receive an new filepackage from [{}] ,pacakge tyep [{}],size [{}],file size [{}]",ctx.channel().remoteAddress().toString(),filePackage.getStatus(),filePackage.getContent()==null?0:filePackage.getContent().remaining(),filePackage.getFileSize());
        if(filePackage.getStatus()== FileStatus.IGNORE){
            return ;
        }
        handler.doHandle(ctx.channel(),filePackage);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        Constants.COMMON_LOGGER.info("unregistered remote socket [{}]",ctx.channel());
        super.channelUnregistered(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }
}
